package com.draemoncode.weixindb.mvc.exception;


import com.draemoncode.weixindb.constant.CharConstant;
import com.draemoncode.weixindb.util.HTTPUtil;
import com.draemoncode.weixindb.util.JSONUtil;
import com.draemoncode.weixindb.util.JvmUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    public static final String DEFAULT_ERROR_VIEW = "error";

    @ExceptionHandler(value = Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest req, HttpServletResponse response, Exception e) throws Exception {
        log.error(e.getMessage(), e);
        if(HTTPUtil.isMobile(req) || HTTPUtil.isAjax(req)){
            if(e != null && (e instanceof BusiException || e.getCause() instanceof BusiException)){
                BusiException busiException = (BusiException) e;
                printResult(response, HttpStatus.BAD_REQUEST, new BusiExceptionVO(busiException.getCode(), busiException.getMessage()));
            }else{
                Map<String, Object> result = new HashMap<>();
                result.put("url", req.getRequestURL() + "  " + req.getMethod());
                result.put("message", e.getMessage());
                result.put("headers", HTTPUtil.showHeaderString(req, CharConstant.HTML_NEW_LINE_CHAR));
                result.put("cookies", HTTPUtil.showCookieString(req, CharConstant.HTML_NEW_LINE_CHAR));
                result.put("params", HTTPUtil.showParamsString(req, CharConstant.HTML_NEW_LINE_CHAR));
                result.put("exception", JvmUtil.printHTMLStackTrace(e, CharConstant.HTML_NEW_LINE_CHAR));
                printResult(response, null, result);
            }
            return new ModelAndView();
        }else{
            ModelAndView mav = new ModelAndView();
            mav.addObject("url", req.getRequestURL() + "  " + req.getMethod());
            mav.addObject("message", e.getMessage());
            mav.addObject("headers", HTTPUtil.showHeaderString(req, CharConstant.HTML_NEW_LINE_CHAR));
            mav.addObject("cookies", HTTPUtil.showCookieString(req, CharConstant.HTML_NEW_LINE_CHAR));
            mav.addObject("params", HTTPUtil.showParamsString(req, CharConstant.HTML_NEW_LINE_CHAR));
            mav.addObject("exception", JvmUtil.printHTMLStackTrace(e, CharConstant.HTML_NEW_LINE_CHAR));
            mav.setViewName(DEFAULT_ERROR_VIEW);
            return mav;
        }
    }

    private void printResult(HttpServletResponse response,HttpStatus httpStatus, Object obj){
        PrintWriter writer = null;
        try {
            if(httpStatus != null){
                response.setStatus(httpStatus.value());
            }else{
                response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            }
            writer = response.getWriter();
            writer.write(JSONUtil.toJson(obj));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            if(writer != null){
                writer.close();
            }
        }
    }

}
